const express=require("express")
const app=express()
const apicache=require("apicache")
const cache=apicache.middleware
const port=9999//端口号
const fs=require("fs")
const path = require("path");

//跨域设置
app.all("*",function(req,res,next){
	if(req.path!=="/" && !req.path.includes(".")){
		res.header("Access-Control-Allow-Credentials", true);
	    // 这里获取 origin 请求头 而不是用 *
	    res.header("Access-Control-Allow-Origin", req.headers["origin"] || "*");
	    res.header("Access-Control-Allow-Headers", "X-Requested-With");
	    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	    res.header("Content-Type", "application/json;charset=utf-8");
	}
	next()
})

const {request,createWebAPIRequest} =require("./until/until.js")
const Wrap = fn => (req, res) => fn(req, res, createWebAPIRequest, request);

//根据路由中的文件名称注册路由

fs.readdirSync(path.resolve(__dirname,"router")).reverse().forEach(file=>{
	if(/\.js$/i.test(file)==false){
		return
	}
	let route
	route='/'+file
	.replace(/\.js$/i,"")
	.replace(/[A-Z]/g,a=>{
		 return "/" + a.toLowerCase();
	})
	app.use(route,Wrap(require("./router/" + file)))
})

app.listen(port,()=>{
	console.log("端口启动"+port)
})
module.exports=app